using System.IO;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Configuration;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class FileSystem : WebService
{
    private static string backupExtension = ConfigurationManager.AppSettings["Backup.Extension"];

    [WebMethod]
    public FileSystemEntry[] GetFileSystemEntries(string folder)
    {
        List<FileSystemEntry> entries = new List<FileSystemEntry>();

        if (!string.IsNullOrEmpty(folder))
        {
            int lastSeparator = folder.LastIndexOf(Path.DirectorySeparatorChar);
            string name = lastSeparator != -1 ? folder.Substring(0, lastSeparator) : "";
            entries.Add(new FileSystemEntry("..", name, true, true));
        }

        string path = HttpContext.Current.Server.MapPath(folder);

        entries.AddRange(CreateEntries(Directory.GetDirectories(path), true));
        entries.AddRange(CreateEntries(Directory.GetFiles(path), false));

        return entries.ToArray();
    }

    [WebMethod]
    public byte[] ReadFile(string path)
    {
        string fullPath = HttpContext.Current.Server.MapPath(path);
        return File.ReadAllBytes(fullPath);
    }

    [WebMethod]
    public void WriteFile(string path, string file, byte[] bytes)
    {
        string fileName = new FileInfo(file).Name;
        string localPath = Path.Combine(path, fileName);
        string fullPath = HttpContext.Current.Server.MapPath(localPath);
        string directory = new FileInfo(fullPath).DirectoryName;

        if (!string.IsNullOrEmpty(backupExtension) && File.Exists(fullPath))
            Backup(fullPath);

        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);

        File.WriteAllBytes(fullPath, bytes);
    }

    private void Backup(string fullPath)
    {
        string backupPath = fullPath + backupExtension;

        if (File.Exists(backupPath))
            Backup(backupPath);

        File.Move(fullPath, backupPath);
    }

    private IEnumerable<FileSystemEntry> CreateEntries(string[] items, bool isDirectory)
    {
        int rootLength = HttpContext.Current.Server.MapPath("").Length + 1;

        foreach (string item in items)
        {
            string name = new FileInfo(item).Name;
            string path = item.Substring(rootLength);
            yield return new FileSystemEntry(name,path, isDirectory, false);
        }
    }
}